package com.example.nutritionmanager

import android.util.Log
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import com.example.nutritionmanager.viewModels.MainViewModel
import androidx.hilt.navigation.compose.hiltViewModel

@Composable
fun SplashScreen(navController: NavController) {
    val mainViewModel: MainViewModel = hiltViewModel()
    val TAG = "SplashScreen"

    LaunchedEffect(Unit) {
        Log.d(TAG, "启动 SplashScreen，开始验证 Token")
        val token = mainViewModel.tokenDataStore.getTokenSync()
        Log.d(TAG, "当前 Token: $token")

        if (token != null) {
            Log.d(TAG, "Token 存在，开始验证有效性")
            mainViewModel.checkTokenValidity(
                onValid = {
                    Log.d(TAG, "Token 有效，导航到首页")
                    navController.navigate("main") {
                        popUpTo("splash") { inclusive = true }
                    }
                },
                onInvalid = { errorMessage ->
                    Log.d(TAG, "Token 无效或过期，导航到登录界面，错误消息: $errorMessage")
                    navController.navigate("login?showExpiredDialog=true") {
                        popUpTo("splash") { inclusive = true }
                    }
                }
            )
        } else {
            Log.d(TAG, "没有找到 Token，导航到登录界面")
            navController.navigate("login?showExpiredDialog=false") {
                popUpTo("splash") { inclusive = true }
            }
        }
    }

    // 显示加载指示器
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier.fillMaxSize()
    ) {
        CircularProgressIndicator()
    }
}
